package red.book._1._2;

import java.util.Arrays;

/**
 * 二分查找非递归， 构造器 自动排序。
 * @author wangbingwu
 *
 */
public class StaticSETofInts {
	private int[] a;

	public StaticSETofInts(int[] keys) {
		a = new int[keys.length];
		for (int i = 0; i < keys.length; i++)
			a[i] = keys[i]; 
		Arrays.sort(a);
	}

	public boolean contains(int key) {
		return rank(key) != -1;
	} 

	private int rank(int key) {
		int start = 0;
		int end = a.length - 1;
		
		while(start <= end) {
			int mid = (start + end) / 2;
			if(a[mid] > key) {
				end = mid - 1;
			}else if(a[mid] < key) {
				start = mid + 1;
			}else {
				return mid;
			}
		}
		
		return -1;
	}
}
